package com.zk.springboot.modules.user.mybatis;

import java.beans.PropertyVetoException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zk.springboot.modules.user.ServiceModule;

/**
 * springboot集成mybatis的基本入口 1）创建数据源(如果采用的是默认的tomcat-jdbc数据源，则不需要)
 * 2）创建SqlSessionFactory 3）配置事务管理器，除非需要使用事务，否则不用配置
 */
@Configuration(ServiceModule.MODULE_NAME+"MyBatisConfig") // 该注解类似于spring配置文件
@PropertySource("classpath:/com/zk/springboot/modules/"+ServiceModule.MODULE_NAME+"/mybatis/DataSourceConfig.properties")
@MapperScan(basePackages = "com.zk.springboot.modules."+ServiceModule.MODULE_NAME+".dao", sqlSessionTemplateRef = ServiceModule.MODULE_NAME+"SqlSessionTemplate")
public class MyBatisConfig {

	@Value("${"+ServiceModule.MODULE_NAME+".datasource.jdbc.driver}")
	private String driver;
	@Value("${"+ServiceModule.MODULE_NAME+".datasource.jdbc.url}")
	private String url;
	@Value("${"+ServiceModule.MODULE_NAME+".datasource.jdbc.username}")
	private String username;
	@Value("${"+ServiceModule.MODULE_NAME+".datasource.jdbc.password}")
	private String password;
	@Value("${"+ServiceModule.MODULE_NAME+".datasource.jdbc.maxIdel}")
	private int maxIdel;
	@Value("${"+ServiceModule.MODULE_NAME+".datasource.jdbc.initialSize}")
	private int initialSize;
	@Value("${"+ServiceModule.MODULE_NAME+".datasource.jdbc.maxActive}")
	private int maxActive;
	@Value("${"+ServiceModule.MODULE_NAME+".datasource.jdbc.checkTime}")
	private int checkTime;
	
	@Autowired
	private Environment env;

	/**
	 * 创建数据源(数据源的名称：方法名可以取为XXXDataSource(),XXX为数据库名称,该名称也就是数据源的名称)
	 *
	 * @Primary 该注解表示在同一个接口有多个实现类可以注入的时候，默认选择哪一个，而不是让@autowire注解报错
	 */
	@Bean(ServiceModule.MODULE_NAME + "DataSource")
	public DataSource DataSource() {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		
		//获取当前启动参数，配置不同分支数据源
		String cfg = env.getProperty("deploy.cfg");
		if(cfg != null) {
			driver = env.getProperty(cfg+"."+ServiceModule.MODULE_NAME+".datasource.jdbc.driver");
			url = env.getProperty(cfg+"."+ServiceModule.MODULE_NAME+".datasource.jdbc.url");
			username = env.getProperty(cfg+"."+ServiceModule.MODULE_NAME+".datasource.jdbc.username");
			password = env.getProperty(cfg+"."+ServiceModule.MODULE_NAME+".datasource.jdbc.password");
			initialSize = env.getProperty(cfg+"."+ServiceModule.MODULE_NAME+".datasource.jdbc.initialSize",Integer.class);
			maxActive = env.getProperty(cfg+"."+ServiceModule.MODULE_NAME+".datasource.jdbc.maxActive",Integer.class);
			maxIdel = env.getProperty(cfg+"."+ServiceModule.MODULE_NAME+".datasource.jdbc.maxIdel",Integer.class);
			checkTime = env.getProperty(cfg+"."+ServiceModule.MODULE_NAME+".datasource.jdbc.checkTime",Integer.class);
		}
		
		try {
			dataSource.setDriverClass(driver);
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		dataSource.setJdbcUrl(url);
		dataSource.setUser(username);
		dataSource.setPassword(password);
		dataSource.setMaxPoolSize(maxActive);
		dataSource.setInitialPoolSize(initialSize);
		dataSource.setMaxIdleTime(maxIdel);
		dataSource.setTestConnectionOnCheckin(true);
		dataSource.setIdleConnectionTestPeriod(checkTime);
		return dataSource;
	}

	/**
	 * 根据数据源创建SqlSessionFactory
	 */
	@Bean(ServiceModule.MODULE_NAME + "SqlSessionFactory")
	public SqlSessionFactory sqlSessionFactoryBean(
			@Qualifier(ServiceModule.MODULE_NAME + "DataSource") DataSource dataSource) {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		try {
			// 添加XML目录
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			bean.setMapperLocations(resolver.getResources("classpath*:com/zk/springboot/modules/"+ServiceModule.MODULE_NAME+"/mapper/*.xml"));
			return bean.getObject();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}

	@Bean(ServiceModule.MODULE_NAME + "SqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(
			@Qualifier(ServiceModule.MODULE_NAME + "SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

	@Bean(ServiceModule.MODULE_NAME + "PlatformTransactionManager")
	public PlatformTransactionManager annotationDrivenTransactionManager(@Qualifier(ServiceModule.MODULE_NAME + "DataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

}